# coding=utf-8

from . import admin
from flask import request, render_template, jsonify
from app import PAGE_NUM, page_code, util
from dbConnection.MysqlConn import Mysql
import math, time, datetime
import sys

reload(sys)
sys.setdefaultencoding('utf8')


# 用户列表
@admin.route('/admin/user_list.html')
@util.admin_login
def user_list_html():
    return render_template('admin/user/user_list.html')


# 获取用户列表数据
@admin.route('/admin/user_list_post', methods=['post'])
@util.admin_login
def user_list_post():
    parms = ['uid', 'day']
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    p = request.values.get('p', default='1')
    c_num = (int(p) - 1) * PAGE_NUM
    sql = "select u.*, if(c.nums, nums, 0) AS user_cp,a.nickname, if(t.wash_num, t.wash_num, 0) wash_num FROM car_users u LEFT JOIN (SELECT count(uid) nums, uid FROM " \
          "car_plate GROUP BY uid) c ON c.uid = u.uid left join user_business as a on a.bid=u.bid LEFT JOIN (SELECT (sum(recharge_num) - sum(use_num)) wash_num, uid from" \
          " user_taocan where now() < end_time GROUP BY uid ) t ON t.uid = u.uid WHERE 1=1"
    sql2 = "select count(uid) AS con FROM car_users WHERE 1=1"
    if maps['uid']:
        sql += " and (u.uid = '%s'" % maps['uid']
        sql += " or u.wxNickName like '%" + maps['uid'] + "%'"
        sql += " or u.phone='%s')" % maps['uid']
        sql2 += " and (uid = '%s'" % maps['uid']
        sql2 += " or wxNickName like '%" + maps['uid'] + "%'"
        sql2 += " or phone='%s')" % maps['uid']
    if maps['day']:
        s_str = maps['day'] + ' 00:00:00'
        e_str = maps['day'] + ' 23:59:59'
        sql += " and u.addTime >= '%s' and u.addTime <= '%s'" % (s_str, e_str)
        sql2 += " and addTime >= '%s' and addTime <= '%s'" % (s_str, e_str)
    sql += " order by u.addTime desc limit %d, %d" % (c_num, PAGE_NUM)
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    if cont:
        pages = math.ceil(cont['con'] / float(PAGE_NUM))
    else:
        pages = 0
    pages = int(pages)
    route_path = 'get_data'
    if pages > 0:
        html_str = page_code.page_code_html_post(int(p), route_path, pages)
    else:
        html_str = ''
    if res:
        for d in res:
            d['addTime'] = str(d['addTime'])
            d['balance'] = str(d['balance'])
            d['wash_num'] = str(d['wash_num'])
        data = {
            'status': 1,
            'res': res,
            'page': html_str,
            'p': p,
            'count':cont['con']
        }
    else:
        data = {
            'status': 2,
            'page': html_str
        }
    return jsonify(data)


# 用户绑定车牌列表
@admin.route('/admin/user_plate.html')
@util.admin_login
def user_plate_list():
    uid = request.args.get('uid')
    sql = "select p.*, u.wxNickName FROM car_plate p LEFT JOIN car_users u ON u.uid = p.uid WHERE p.uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return render_template('admin/user/user_plate.html', res=res, uid=uid)


# 删除车牌
@admin.route('/admin/delete_plate_post', methods=['post'])
@util.admin_login
def delete_plate_post():
    data = {}
    data['status'] = 0
    pid = request.values.get('pid')
    uid = request.values.get('uid')
    user = get_user(uid)
    if user is None:
        data['status'] = 2
        return jsonify(data)
    res = delete_plate(uid, pid)
    if res > 0:
        data['status'] = 1
    return jsonify(data)


# 添加车牌
@admin.route('/admin/add_user_plate', methods=['post'])
@util.admin_login
def add_user_plate():
    data = {}
    data['status'] = 0
    uid = request.values.get('uid')
    plate = request.values.get('plate')
    user = get_user(uid)
    if user is None:
        data['status'] = 2
        return jsonify(data)
    num = get_user_plate_num(uid)
    if int(num) > 2:
        data['status'] = 3
        return jsonify(data)
    user_plate = get_user_plate(uid, plate)
    if user_plate:
        data['status'] = 4
        return jsonify(data)
    res = add_plate(uid, plate)
    if res > 0:
        data['status'] = 1
    return jsonify(data)


# 用户绑定车牌详情
@admin.route('/admin/user_plate', methods=['post'])
@util.admin_login
def user_plate():
    uid = request.values.get('uid')
    sql = "select * FROM car_plate WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    data = {}
    data['status'] = 0
    data['data'] = []
    if res:
        for d in res:
            d['add_time'] = str(d['add_time'])
        data['status'] = 1
        data['data'] = res
    return jsonify(data)


# 禁用用户
@admin.route('/admin/stop_user_post', methods=['post'])
@util.admin_login
def stop_user_post():
    uid = request.values.get('uid')
    sql = "update car_users SET status = 0 WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return jsonify(data)


# 激活用户
@admin.route('/admin/jh_user_post', methods=['post'])
@util.admin_login
def jh_user_post():
    uid = request.values.get('uid')
    sql = "update car_users SET status = 1 WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return jsonify(data)


# 解绑用户
@admin.route('/admin/unbind', methods=['post'])
@util.admin_login
def admin_user_unbind():
    uid = request.values.get('uid')
    sql = "update car_users SET bid = 0 WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return jsonify(data)


# 删除用户
@admin.route('/admin/delete_user_post', methods=['post'])
@util.admin_login
def delete_user_post():
    uid = request.values.get('uid')
    sql = "delete FROM  car_users WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.delete(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return jsonify(data)


# 编辑用户资料
@admin.route('/admin/user_edit.html')
@util.admin_login
def user_edit():
    uid = request.args.get('uid')
    sql = "select u.*, if(c.nums, c.nums, 0) user_cp,a.nickname FROM car_users u LEFT JOIN (SELECT count(uid) nums, uid FROM " \
          "car_plate WHERE uid = '%s') c ON c.uid = u.uid left join user_business as a on u.bid=a.bid WHERE u.uid = '%s'" % (
              uid, uid)
    sql2 = "select bid,nickname from user_business where status=1 "
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    result = mysql.getAll(sql2, None)
    mysql.dispose()
    return render_template('admin/user/user_edit.html', res=res, result=result)


# 修改用户资料
@admin.route('/admin/user_edit_post', methods=['post'])
@util.admin_login
def user_edit_post():
    uid = request.values.get('uid')
    phone = request.values.get('phone')
    washNum = request.values.get('washNum')
    bid = request.values.get('bid')
    sql = "update car_users SET phone = '%s', washNum = '%s',bid='%s' WHERE uid = '%s'" % (phone, washNum, bid, uid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return jsonify(data)


# 用户绑定列表
@admin.route('/admin/bind/list.html', methods=['post', 'get'])
@util.admin_login
def admin_bind_list():
    bid = request.args.get('bid')
    mysql = Mysql()
    sql = "select * from car_users where bid='%s'" % bid
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return render_template('admin/business/bind_list.html', res=res)


@admin.route('/admin/user/suit.html', methods=['POST', 'GET'])
@util.admin_login
def admin_user_suit():
    uid = request.values.get('uid')
    page = request.values.get('page', default=1)
    page = int(page)
    num = (int(page) - 1) * util.PAGE_NUM
    mysql = Mysql()
    sql = "select * from user_taocan where uid='%s' order by id desc limit %d,%d" % (uid, num, util.PAGE_NUM)
    sql2 = "select count(*) from  user_taocan where uid='%s'" % uid
    res = mysql.getAll(sql, None)
    count = mysql.getOne(sql2, None)
    count = int(count['count(*)'])
    mysql.dispose()
    if res:
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        for x in res:
            if current_time > str(x['end_time']):
                x['period'] = u"已过期"
            else:
                x['period'] = u"未过期"
            x['odd'] = x['recharge_num'] - x['use_num']
    if count % util.PAGE_NUM > 0:
        max_page = count / util.PAGE_NUM + 1
    else:
        max_page = count / util.PAGE_NUM
    data = {
        'res': res,
        'max_page': max_page,
        'page': page,
        'uid': str(uid)
    }
    return render_template('admin/user/user_suit.html', res=data)


# 获取用户
def get_user(uid):
    sql = "select * FROM car_users WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 删除车牌
def delete_plate(uid, pid):
    sql = "delete FROM car_plate WHERE id = '%s' AND uid = '%s'" % (pid, uid)
    mysql = Mysql()
    res = mysql.delete(sql, None)
    mysql.dispose()
    return res


# 获取用户车牌
def get_user_plate(uid, plate):
    sql = "select * FROM car_plate WHERE uid = '%s' AND license_plate = '%s'" % (uid, plate.upper())
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 获取用户绑定的车牌数
def get_user_plate_num(uid):
    sql = "select count(*) con FROM car_plate WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res['con'] if res else 0


# 新增车牌
def add_plate(uid, plate):
    sql = "insert INTO car_plate(uid, license_plate, add_time) VALUES ('%s', '%s', now())" % (uid, plate.upper())
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res